<?php

class Util {

	/**
	 * 通过curl取得用户数据
	 * 
	 * @param string $url
	 */
	public function getHttpRequest($url)
	{
		$options = array(
			CURLOPT_RETURNTRANSFER => true,         // return web page
			CURLOPT_HEADER         => false,        // don't return headers
			CURLOPT_NOSIGNAL      => true,
			CURLOPT_CONNECTTIMEOUT_MS => 200,       // 发起连接的等待时间
			CURLOPT_TIMEOUT        => 2,     	    // curl执行时间
			CURLOPT_SSL_VERIFYHOST => 0,            // don't verify ssl
			CURLOPT_SSL_VERIFYPEER => false,        //
		);

		$ch = curl_init($url);
		curl_setopt_array($ch,$options);
		$rtn = curl_exec($ch);
		curl_close($ch);
		if($rtn == null || $rtn == ''){
			return false;
		}else{
			return $rtn;
		}
	}

	/**
	 * HTTP内容请求辅助函数
	 * string $url 请求的url地址
	 * array $data POST数据
	 * array $headers 发送的http头信息
	 * array $options curl的参数
	 */
	public function httpfetch($url, $data=null, $headers = array(), $options = array()) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		if (!empty($options)) {
			curl_setopt_array($ch, $options);
		}

		if (!empty($headers)) curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		if (!empty($data)){
			curl_setopt($ch, CURLOPT_POST, 1);

			if (is_array($data)) {
				$postdata = '';
				foreach ($data as $key => $val) {
					//$postdata .= $key . '=' . urlencode($val) . '&';
					$postdata .= $key . '=' . $val . '&';
				}
				$data = trim($postdata, '&');
			}

			curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		}
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		// 设置连接超时时间 2 秒
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
		// 设置超时时间 10 秒
		curl_setopt($ch,CURLOPT_TIMEOUT,20);
		$out = curl_exec($ch);
		if ($out === false) {
			_logger(_LL_ERROR, 'Connect failed: ' . $url);
		} else {
			$out = trim($out);
		}
		curl_close($ch);
		// _logger(_LL_DEBUG, "content: $url, RESULT: $out");
		// $out = json_decode($out, true); 
		return $out;
	}

}

?>
